﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;

using MiniSched.Email.Messages;
using MiniSched.Email.Abstractions;
using MiniSched.Logging;

namespace MiniSched.Email {
    public class MiniSchedEmailer {

        private static readonly MiniSchedLog Log = MiniSchedLogFactory.Default.CreateLogFor<MiniSchedEmailer>();

        internal SmtpClientAbstraction SmtpClientAbstraction {
            get {
                if (null == _SmtpClientAbstraction) _SmtpClientAbstraction = new SmtpClientAbstraction();
                return _SmtpClientAbstraction;
            }
            set {
                if (null == value) throw new ArgumentNullException("SmtpClientAbstraction");
                _SmtpClientAbstraction = value;
            }
        }
        private SmtpClientAbstraction _SmtpClientAbstraction;

        public int SendAttemptCount {
            get { return _SendAttemptCount; }
            set { _SendAttemptCount = value; }
        }
        private int _SendAttemptCount = 3;

        public void Send(MiniSchedMessage message) {
            if (null == message) throw new ArgumentNullException("message");

            var mailMessage = message.MailMessage;

            SmtpClientAbstraction.SendMailAsync(mailMessage).ContinueWith(t => {

                if (t.IsFaulted) {
                    Log.Warn("An error occurred while sending a message.", t.Exception);

                    var attempt = 0;
                    var maxAttempt = SendAttemptCount;

                    while (maxAttempt > ++attempt) {

                        try {
                            SmtpClientAbstraction.Send(mailMessage);
                            return;
                        }
                        catch (Exception ex) {
                            Log.Warn("An error occurred while sending a message on attempt " + attempt + ".", ex);
                        }
                    }

                    Log.Error("A message was unable to be sent after " + maxAttempt + " attempts.");
                }
            });
        }
    }
}
